<template>
  <el-drawer
    v-model="visible"
    direction="rtl"
    :with-header="false"
    :size="drawerSize"
    @open="handleDrawerOpen"
    :class="drawerClass"
  >
    <zz-Label
      :text="$t('table.columnSettings')"
      style="margin-bottom: 20px"
    ></zz-Label>
    <div class="column-setting-content">
      <div class="column-list" :id="listId" ref="columnListRef">
        <div
          v-for="(column, index) in localColumns"
          :key="column.field"
          class="column-item"
          :class="{
            'column-left-fixed': column.fixed === 'left',
            'column-right-fixed': column.fixed === 'right',
          }"
          :data-index="index"
        >
          <div class="column-content">
            <div class="column-checkbox-wrapper">
              <el-checkbox
                :model-value="column.visible"
                @change="(val) => handleColumnVisibleChange(column, val)"
                class="column-checkbox"
              >
                <span class="column-title draggable-text">{{
                  column.title
                }}</span>
              </el-checkbox>
              <div class="column-actions">
                <!-- 固定状态指示器 -->
                <span v-if="column.fixed" class="fixed-indicator">
                  <el-icon class="fixed-icon" @click="cancelFixed(column)">
                    <Close />
                  </el-icon>
                  <span class="fixed-text">{{
                    column.fixed === "left"
                      ? $t("component.table.leftFixed")
                      : $t("component.table.rightFixed")
                  }}</span>
                </span>
                <!-- 悬浮时显示的操作按钮 -->
                <div class="hover-actions">
                  <el-icon
                    class="action-btn left-btn"
                    @click="setColumnFixed(column, 'left')"
                    :title="$t('component.table.leftFixed')"
                  >
                    <ArrowLeft />
                  </el-icon>
                  <el-icon
                    class="action-btn right-btn"
                    @click="setColumnFixed(column, 'right')"
                    :title="$t('component.table.rightFixed')"
                  >
                    <ArrowRight />
                  </el-icon>
                </div>
                <el-icon v-if="!column.fixed" class="drag-icon">
                  <Rank />
                </el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleCancel">{{ $t("common.cancel") }}</el-button>
        <el-button @click="handleReset">{{ $t("common.reset") }}</el-button>
        <el-button type="primary" @click="handleConfirm">{{
          $t("common.confirm")
        }}</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, computed, getCurrentInstance, nextTick, watch } from "vue";
import { useI18n } from "vue-i18n";
import Sortable from "sortablejs";
const { proxy } = getCurrentInstance();
import {
  Close,
  ArrowLeft,
  ArrowRight,
  Operation as DragIcon,
} from "@element-plus/icons-vue";

const { t } = useI18n();

// Props定义
const props = defineProps({
  // 控制抽屉显示/隐藏
  modelValue: {
    type: Boolean,
    default: false,
  },
  // 列配置数据
  columns: {
    type: Array,
    required: true,
    default: () => [],
  },
  // 默认列配置（用于重置）
  defaultColumns: {
    type: Array,
    default: () => [],
  },
  // 抽屉尺寸
  drawerSize: {
    type: String,
    default: "350px",
  },
  // 抽屉CSS类名
  drawerClass: {
    type: String,
    default: "column-setting-drawer",
  },
  // 列表容器ID（用于拖拽）
  listId: {
    type: String,
    default: "column-list",
  },
  // 本地存储键名
  storageKey: {
    type: String,
    default: "",
  },
});

// Emits定义
const emit = defineEmits([
  "update:modelValue",
  "confirm",
  "cancel",
  "reset",
  "column-change",
]);

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

// 本地列配置（用于编辑）
const localColumns = ref([]);
// 备份列配置（用于取消操作）
const columnsBackup = ref([]);
// 拖拽实例
let sortableInstance = null;

// 监听columns变化，同步到本地
watch(
  () => props.columns,
  (newColumns) => {
    if (newColumns && newColumns.length > 0) {
      // 深拷贝确保不影响原始数据
      localColumns.value = JSON.parse(JSON.stringify(newColumns));

      // 如果抽屉已打开，重新初始化拖拽
      if (visible.value) {
        nextTick(() => {
          initSortable();
        });
      }
    }
  },
  { immediate: true, deep: true }
);

// 处理抽屉打开
const handleDrawerOpen = () => {
  // 备份当前列设置
  columnsBackup.value = JSON.parse(JSON.stringify(localColumns.value));

  // 确保列数据已加载
  if (localColumns.value.length === 0 && props.columns.length > 0) {
    localColumns.value = JSON.parse(JSON.stringify(props.columns));
  }

  // 初始化拖拽，使用setTimeout确保DOM已完全渲染
  setTimeout(() => {
    initSortable();
  }, 300);
};

// 列表容器ref
const columnListRef = ref(null);

// 初始化拖拽功能
const initSortable = () => {
  nextTick(() => {
    // 优先使用ref引用，如果不可用则尝试使用ID查找
    const container =
      columnListRef.value || document.getElementById(props.listId);

    if (container) {
      // 销毁之前的实例
      if (sortableInstance) {
        sortableInstance.destroy();
        sortableInstance = null;
      }

      // 创建新的Sortable实例
      sortableInstance = Sortable.create(container, {
        handle: ".drag-icon", // 使用拖拽图标作为拖拽手柄
        animation: 150,
        ghostClass: "sortable-ghost",
        chosenClass: "sortable-chosen",
        dragClass: "sortable-drag",
        filter: ".column-left-fixed, .column-right-fixed", // 过滤掉固定的列
        preventOnFilter: true, // 阻止过滤元素的默认事件
        onMove: (evt) => {
          // 阻止拖拽到固定列的位置
          const related = evt.related;
          if (!related) return true;

          return (
            !related.classList.contains("column-left-fixed") &&
            !related.classList.contains("column-right-fixed")
          );
        },
        onEnd: ({ newIndex, oldIndex }) => {
          // 确保索引有效
          if (newIndex === oldIndex || newIndex < 0 || oldIndex < 0) return;

          // 更新列顺序
          const currRow = localColumns.value.splice(oldIndex, 1)[0];
          localColumns.value.splice(newIndex, 0, currRow);

          // 强制更新视图
          localColumns.value = [...localColumns.value];

          // 触发拖拽结束事件
          handleColumnDragEnd(localColumns.value);
        },
      });
    } else {
      console.warn("未找到拖拽容器元素: " + props.listId);
    }
  });
};

// 处理列显示/隐藏
const handleColumnVisibleChange = (column, visible) => {
  // 直接通过索引找到对应的列，避免引用问题
  const index = localColumns.value.findIndex(
    (col) => col.field === column.field
  );
  if (index !== -1) {
    // 创建一个新对象来更新可见性，确保响应式更新
    localColumns.value[index] = {
      ...localColumns.value[index],
      visible: visible,
    };

    // 强制更新视图
    localColumns.value = [...localColumns.value];

    emit("column-change", {
      type: "visible",
      column: localColumns.value[index],
      value: visible,
    });
  }
};

// 设置列固定
const setColumnFixed = (column, fixed) => {
  const index = localColumns.value.findIndex(
    (col) => col.field === column.field
  );
  if (index !== -1) {
    // 创建一个新对象来更新固定状态，确保响应式更新
    localColumns.value[index] = {
      ...localColumns.value[index],
      fixed: fixed,
    };

    // 自动排序：左固定移到最上面，右固定移到最下面
    sortColumnsByFixed();

    // 强制更新视图
    localColumns.value = [...localColumns.value];

    emit("column-change", {
      type: "fixed",
      column: localColumns.value[index],
      value: fixed,
    });
  }
};

// 取消列固定
const cancelFixed = (column) => {
  const index = localColumns.value.findIndex(
    (col) => col.field === column.field
  );
  if (index !== -1) {
    // 创建一个新对象来更新固定状态，确保响应式更新
    localColumns.value[index] = {
      ...localColumns.value[index],
      fixed: null,
    };

    // 自动排序
    sortColumnsByFixed();

    // 强制更新视图
    localColumns.value = [...localColumns.value];

    emit("column-change", {
      type: "fixed",
      column: localColumns.value[index],
      value: null,
    });
  }
};

// 列按固定状态排序
const sortColumnsByFixed = () => {
  const leftFixed = localColumns.value.filter((col) => col.fixed === "left");
  const normal = localColumns.value.filter((col) => !col.fixed);
  const rightFixed = localColumns.value.filter((col) => col.fixed === "right");
  localColumns.value = [...leftFixed, ...normal, ...rightFixed];
};

// 处理列拖拽排序
const handleColumnDragEnd = (newColumns) => {
  emit("column-change", {
    type: "sort",
    columns: newColumns,
  });
};

// 处理取消
const handleCancel = () => {
  // 恢复备份的列设置
  localColumns.value = JSON.parse(JSON.stringify(columnsBackup.value));
  visible.value = false;
  emit("cancel");
};

// 处理重置
const handleReset = () => {
  // 恢复默认列设置
  if (props.defaultColumns.length > 0) {
    localColumns.value = JSON.parse(JSON.stringify(props.defaultColumns));

    // 重新初始化拖拽
    nextTick(() => {
      initSortable();
    });

    // // 发送重置事件，传递重置后的列设置
    // const columnsCopy = JSON.parse(JSON.stringify(localColumns.value));
    // emit("reset", columnsCopy);
  } else {
    console.warn("未提供默认列设置，无法重置");
  }
};

// 处理确认
const handleConfirm = () => {
  // 保存到本地存储
  if (props.storageKey) {
    const STORAGE_KEY = proxy.$CONS.STORAGE_KEY;
    // 读取现有的所有表格设置
    const allSettings = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
    // 更新当前表的列设置
    allSettings[props.storageKey] = localColumns.value;
    // 写回本地存储
    localStorage.setItem(STORAGE_KEY, JSON.stringify(allSettings));
  }

  // 关闭抽屉
  visible.value = false;

  // 发送确认事件，传递列设置
  const columnsCopy = JSON.parse(JSON.stringify(localColumns.value));
  emit("confirm", columnsCopy);
};

// 销毁拖拽实例
const destroySortable = () => {
  if (sortableInstance) {
    sortableInstance.destroy();
    sortableInstance = null;
  }
};

// 组件卸载时清理
import { onUnmounted } from "vue";
onUnmounted(() => {
  destroySortable();
});
</script>

<style scoped>
.column-setting-content {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.column-list {
  flex: 1;
  /* overflow-y: auto; */
}

.column-item {
  margin-bottom: 12px;
  padding: 12px;
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  background: var(--el-bg-color);
  transition: all 0.3s ease;
  cursor: move;
}

.column-item:hover {
  border: 1px solid var(--el-color-primary);
  box-shadow: 0 4px 12px var(--el-box-shadow-light);
}

/* 列内容容器 */
.column-content {
  width: 100%;
}

/* 列操作区域 */
.column-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 固定状态指示器 */
.fixed-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 2px 6px;
  background-color: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary);
  border-radius: 4px;
  font-size: 12px;
  color: var(--el-color-primary);
}

.fixed-icon {
  font-size: 12px;
  cursor: pointer;
  transition: color 0.3s;
}

.fixed-icon:hover {
  color: var(--el-color-danger);
}

.fixed-text {
  font-size: 12px;
  white-space: nowrap;
}

/* 悬浮时显示的操作按钮 */
.hover-actions {
  display: none;
  gap: 4px;
}

/* 未固定的列悬浮时显示操作按钮 */
.column-item:not(.column-left-fixed):not(.column-right-fixed):hover
  .hover-actions {
  display: flex;
}

.action-btn {
  padding: 4px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 20px;
  color: var(--el-text-color-placeholder);
}

.action-btn:hover {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

.left-btn:hover {
  background-color: var(--el-color-success-light-9);
  color: var(--el-color-success);
}

.right-btn:hover {
  background-color: var(--el-color-warning-light-9);
  color: var(--el-color-warning);
}

.column-checkbox-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.column-checkbox {
  flex: 1;
  margin-right: 12px;
}

.column-checkbox :deep(.el-checkbox__label) {
  font-weight: 500;
}

.column-title {
  font-size: 14px;
  color: var(--el-text-color-regular);
  cursor: move;
  user-select: none;
  padding: 4px 0;
  transition: color 0.3s;
}

.column-title:hover {
  color: var(--el-color-primary);
}

.drag-icon {
  color: var(--el-text-color-placeholder);
  cursor: move;
  font-size: 20px;
  transition: all 0.3s ease;
  padding: 4px;
  border-radius: 4px;
}

.drag-icon:hover {
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}

.drag-icon:active {
  color: var(--el-color-primary-dark-2);
  background-color: var(--el-color-primary-light-8);
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  padding: 20px;
  border-top: 1px solid var(--el-border-color);
  margin: 0 -20px -20px -20px;
}

/* 拖拽状态样式 */
.sortable-ghost {
  opacity: 0.5;
  background-color: var(--el-fill-color-light);
  border: 1px dashed var(--el-color-primary);
}

.sortable-chosen {
  background-color: var(--el-color-primary-light-9);
  border: 1px dashed var(--el-color-primary);
  transform: scale(1.02);
}

.sortable-drag {
  opacity: 0.8;
  background-color: var(--el-bg-color);
  box-shadow: var(--el-box-shadow);
  transform: rotate(5deg);
}

.draggable-text {
  transition: all 0.3s;
}

/* 固定列的特殊样式 */
.column-left-fixed {
  border-left: 3px solid var(--el-color-success);
  background: linear-gradient(
    90deg,
    var(--el-color-success-light-9) 0%,
    var(--el-bg-color) 100%
  );
}

.column-right-fixed {
  border-left: 3px solid var(--el-color-warning);
  background: linear-gradient(
    90deg,
    var(--el-color-warning-light-9) 0%,
    var(--el-bg-color) 100%
  );
}

.column-left-fixed:hover {
  border-color: var(--el-color-success);
  box-shadow: 0 4px 12px var(--el-color-success-light-7);
}

.column-right-fixed:hover {
  border-color: var(--el-color-warning);
  box-shadow: 0 4px 12px var(--el-color-warning-light-7);
}
</style>
